package com.qcs.sleep.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import com.qcs.sleep.R;
import com.qcs.sleep.SplashActivity;
import com.qcs.sleep.OnWarnListener;
import com.qcs.sleep.broadcast.PowerOnBroadcast;
import com.qcs.sleep.warn.EyeWarnAdapter;
import com.qcs.sleep.warn.LauncherWarnAdapter;
import com.qcs.sleep.warn.LongTimeWarnAdapter;
import com.qcs.sleep.warn.NightWarnAdapter;
import com.qcs.sleep.warn.SoundWarnAdapter;
import com.qcs.sleep.warn.VideoWarnAdapter;
import com.qcs.sleep.warn.WarnAdapter;
import com.qcs.sleep.warn.WebWarnAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by chshqiang on 13-10-2.
 * 困了睡的主要服务进程
 */
public class SleepListenerServicer extends Service {
    private final SleepListenerBinder mBinder = new SleepListenerBinder();

    private BroadcastReceiver receiver;
    private ActivityManager activityManager;

    private Timer timer;
    private TimerTask task;
    private Handler handler;

    // 所有的警示适配器
    private List<WarnAdapter> adapterList;
    private OnWarnListener listener;

    // 当前警示类别
    private Warn warn;
    private String topAppAddActivity; // 当前顶层的应用包名及Activity名，两者以斜杆区别
    private boolean isMusicActive;

    @Override
    public void onCreate() {
        super.onCreate();

        activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);


        warn = new Warn();
        adapterList = new ArrayList<WarnAdapter>();
        listener = new SleepOnWarnListener();

        receiver = new SleepBroadcastReceiver();

        task = new TimerTask() {
            @Override
            public void run() {
                SleepListenerServicer.this.run();
            }
        };
        timer = new Timer();

        handler = new ExecuteHandler();

        init();
    }

    private void init() {
        warn.clear();

        EyeWarnAdapter eyeWarnAdapter = new EyeWarnAdapter();
        eyeWarnAdapter.setOnWarnListener(listener);
        LongTimeWarnAdapter longTimeWarnAdapter = new LongTimeWarnAdapter();
        longTimeWarnAdapter.setOnWarnListener(listener);
        NightWarnAdapter nightWarnAdapter = new NightWarnAdapter();
        nightWarnAdapter.setOnWarnListener(listener);
        SoundWarnAdapter soundWarnAdapter = new SoundWarnAdapter();
        soundWarnAdapter.setOnWarnListener(listener);
        VideoWarnAdapter videoWarnAdapter = new VideoWarnAdapter();
        videoWarnAdapter.setOnWarnListener(listener);
        WebWarnAdapter webWarnAdapter = new WebWarnAdapter();
        webWarnAdapter.setOnWarnListener(listener);

        adapterList.add(eyeWarnAdapter);
        adapterList.add(longTimeWarnAdapter);
        adapterList.add(nightWarnAdapter);
        adapterList.add(soundWarnAdapter);
        adapterList.add(videoWarnAdapter);
        adapterList.add(webWarnAdapter);

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction("android.intent.action.PHONE_STATE");
        filter.addAction("android.intent.action.NEW_OUTGOING_CALL");

        registerReceiver(receiver, filter);

        timer.schedule(task, 10L, 1000L);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        warn.clear();

        for (WarnAdapter adapter : adapterList) {
            adapter.onReceive(intent.getStringExtra(PowerOnBroadcast.KEY));
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class SleepListenerBinder extends Binder {
        SleepListenerServicer getService() {
            return SleepListenerServicer.this;
        }
    }

    private void run() {
        check();

        for (WarnAdapter adapter : adapterList) {
            if (adapter instanceof LauncherWarnAdapter)
                ((LauncherWarnAdapter) adapter).onReceive(LauncherWarnAdapter.APP, topAppAddActivity);

            adapter.onReceive(isMusicActive ? Action.MUSIC_ON : Action.MUSIC_OFF);

            adapter.run();
        }

        handler.sendEmptyMessage(0);
    }

    private void execute() {
//        Log4J.m(warn.toString());

        String msg = null == warn.obj ? getString(R.string.default_tip) : warn.obj.toString();

        switch (warn.flag) {
            case OnWarnListener.FLAG_TOAST:
                Toast.makeText(SleepListenerServicer.this, msg, Toast.LENGTH_LONG).show();
                break;

            case OnWarnListener.FLAG_DIALOG:
                break;

            case OnWarnListener.FLAG_ACTIVITY:
                sendWarn(msg);
                break;

            case OnWarnListener.FLAG_SCENCE_OFF:
                break;

            case OnWarnListener.FLAG_VOLUME:
                break;

            default:
                break;
        }

        if (0 != warn.flag)
            warn.clear();
    }

    private void sendWarn(String msg) {
        Intent t = new Intent();
        t.setClass(SleepListenerServicer.this, SplashActivity.class);
        t.putExtra("msg", msg);
        t.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        startActivity(t);
    }

    private void check() {
        topAppAddActivity = "";

        List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
        ComponentName componentInfo = null == taskInfo ? null : taskInfo.get(0).topActivity;

        topAppAddActivity = null == componentInfo ? "" : componentInfo.getPackageName();

        if ("com.qcs.sleep".equals(topAppAddActivity)) {
            warn.clear();
            warn.level = 69;
        } else {
            if (69 == warn.level)
                warn.clear();
        }

        topAppAddActivity += "/" + (null == componentInfo ? "" : componentInfo.getClassName());

        isMusicActive = ((AudioManager) getSystemService(Context.AUDIO_SERVICE)).isMusicActive();
    }

    class Warn {
        int level;
        int flag;
        Object obj;

        public void clear() {
            level = 0;
            flag = 0;
            obj = null;
        }

        @Override
        public String toString() {
            return "Warn{" +
                    "level=" + level +
                    ", flag=" + flag +
                    ", obj=" + obj +
                    "} " + super.toString();
        }
    }

    class ExecuteHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            execute();
        }
    }

    class SleepOnWarnListener implements OnWarnListener {

        @Override
        public void onWarn(int level, int flag, Object obj) {
            if (level < warn.level)
                return;
            else if (level == warn.level && flag < warn.flag)
                return;
            else if (level == warn.level && flag == warn.flag && null == obj)
                return;

            warn.level = level;
            warn.flag = flag;
            warn.obj = obj;
        }

    }

    class SleepBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            for (WarnAdapter adapter : adapterList) {
                adapter.onReceive(intent.getAction());
            }

            if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) { // 黑屏后，示警强度变为预留强度
                warn.clear();
                warn.level = 79;
//            } else if (Intent.ACTION_NEW_OUTGOING_CALL.equals(intent.getAction())
//                    || "android.intent.action.PHONE_STATE".equals(intent.getAction())) {
//                warn.clear();
//                warn.level = 89;
            }
        }
    }

}
